package com.losers;



import java.util.ArrayList;

import java.util.List;

import android.opengl.Matrix;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.LayoutInflater;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;

public class BeerForm extends Activity {

	static public final String INTENT_BEER_ID = "beerId";
	
	private ArrayAdapter<String> adapter;
	private List<String> model = new ArrayList<String>();
    private static final int DIALOG_YES_NO_MESSAGE = 1;

    public static final int NOTIFICATION_SERVICE_STARTED = 1;
	
	// Widgets
	EditText wName;
	EditText wBrewery;
	Spinner wType;
	RatingBar wRating;
	EditText wAbv;
	EditText wDescription;
	ImageView wPicture;
	
	
	// Database stuff
	SQLiteDatabase db = null;
	String beerId;
	
	// Adapter for spinner
	//CursorAdapter adapter
	
	Beer beer;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			
		setContentView(R.layout.beer);
	
		// Find widgets
		wName = (EditText)findViewById(R.id.EditTextName);
		wBrewery = (EditText)findViewById(R.id.EditTextBrewery);
		wAbv = (EditText)findViewById(R.id.EditTextAbv);
		wType = (Spinner)findViewById(R.id.SpinnerType);
		wDescription = (EditText)findViewById(R.id.EditTextDescription);
		wRating = (RatingBar)findViewById(R.id.RatingBarRating);
		wPicture = (ImageView)findViewById(R.id.ImageButton);
			
		db = (new Database(this)).getWritableDatabase();
		
		// Fill spinner (before selecting any spinner value)<
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, model);
	    wType.setAdapter(adapter);
	    fillTypes(db, adapter);
		
	    // If beer is clicked then it's id is send via intent
		beerId = getIntent().getStringExtra(INTENT_BEER_ID);
	    
		if (beerId != null) {
			beer = Beer.getById(beerId, db);
			
			wName.setText(beer.getName());
			wBrewery.setText(beer.getBrewery());
			wAbv.setText(beer.getAbv());
			wDescription.setText(beer.getDescription());
			wRating.setRating(beer.getRating());
			wType.setSelection(beer.getType());

			if (beer.getPicture() != null) {
				int width = beer.getPicture().getWidth(); 
		        int height = beer.getPicture().getHeight(); 
		        
		        // Create matrix to scale image size
		        float scaleWidth = 132.0f / beer.getPicture().getWidth();
		        float scaleHeight = 132.0f / beer.getPicture().getHeight();
		        
		        android.graphics.Matrix matrix = new android.graphics.Matrix(); 
		        matrix.postScale(scaleWidth, scaleHeight); 
				Bitmap resizedBitmap = Bitmap.createBitmap(beer.getPicture(), 0, 0, width, height, matrix, true);
				wPicture.setImageBitmap(resizedBitmap);
			}
	 		
	 		
			//wPicture.setImageBitmap(beer.getPicture());		
		}
		else beer = new Beer();
		
		wRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){
			
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
				wRating.setRating(rating);
				Toast.makeText(BeerForm.this, "rating:"+String.valueOf(rating),
				Toast.LENGTH_LONG).show();
			}});
	}
	
	private void fillTypes(SQLiteDatabase db, ArrayAdapter<String> adapter) {
		Cursor cursor = db.query("type", new String[]{"name"}, null, null, null, null, "name");
		if (cursor.moveToFirst()) {
			do {
				adapter.add(cursor.getString(0)); 
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
	}
	
	public void onBackClicked(View v) {
		finish();
	}
	
	public void onSaveBeerClicked(View v) {
		
		beer.setName(wName.getText().toString());
		beer.setBrewery(wBrewery.getText().toString());
		beer.setAbv(wAbv.getText().toString());
		beer.setDescription(wDescription.getText().toString());
		beer.setRating(wRating.getRating());
		beer.setType((int)wType.getSelectedItemId());
		//beer.setPicture(wPicture.get);
		
		// Save modifications to database
		if (beerId != null) beer.update(beerId, db);
		else beer.save(db);
		
		showServiceStartedNotification();
		dismissServiceStartedNotification();
		finish();
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
    	
            return new AlertDialog.Builder(BeerForm.this)
                
            	.setTitle(R.string.AlertMessage)
            	.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

            
                    	//TODO Poista BeerID tietokannasta
                    	//db.execSQL("DELETE FROM beer WHERE _id = ?",)
                    	db.delete("beer", "_id=?", new String[]{beerId});
                    	finish();
                		showServiceStartedNotification();
                		dismissServiceStartedNotification();
                    }
                })
                .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                     
                    }
                })
                .create();
    }

	public void onRemoveClicked(View v){
	
        showDialog(DIALOG_YES_NO_MESSAGE);
	}
	
	public void onPictureClicked(View v) {
		
		PictureForm.bmp = beer.getPicture();
		
		Intent intent = new Intent(BeerForm.this, PictureForm.class);
		//intent.putExtra(BeerForm.INTENT_BEER_ID, String.valueOf(id));
		startActivityForResult(intent, PictureForm.REQUEST_PICTURE_DATA);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PictureForm.REQUEST_PICTURE_DATA) {
			// camera activity has ended, update image view
           	if (PictureForm.bmp != null) {
         		beer.setPicture(PictureForm.bmp);
         		
         		int width = beer.getPicture().getWidth(); 
		        int height = beer.getPicture().getHeight(); 
		        
		        // Create matrix to scale image size
		        float scaleWidth = 132.0f / beer.getPicture().getWidth();
		        float scaleHeight = 132.0f / beer.getPicture().getHeight();
		        
		        android.graphics.Matrix matrix = new android.graphics.Matrix(); 
		        matrix.postScale(scaleWidth, scaleHeight); 
				Bitmap resizedBitmap = Bitmap.createBitmap(beer.getPicture(), 0, 0, width, height, matrix, true);
				wPicture.setImageBitmap(resizedBitmap);
         		
         		//Bitmap resizedBitmap = Bitmap.createBitmap(beer.getPicture(), 0, 0, 132, 132);
         		//wPicture.setImageBitmap(resizedBitmap);         
           	}
        }
    }
	
	// Notification example from Monday's Android presentation
	
	private void showServiceStartedNotification() {
		Notification notification = new Notification(android.R.drawable.star_big_on,
		getString(R.string.noteServiceStarted_tickerText), System.currentTimeMillis());
		
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		String contentTitle = getString(R.string.noteServiceStarted_contentTitle);
		String contentText = getString(R.string.noteServiceStarted_contentText);

		Intent notificationIntent = new Intent(BeerForm.this, BeerForm.class);
		Context applicationContext = getApplicationContext();
		
		PendingIntent contentIntent = PendingIntent.getActivity(applicationContext, 0, notificationIntent, 0);
		notification.setLatestEventInfo(applicationContext, contentTitle, contentText, contentIntent);
		NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		
		manager.notify(NOTIFICATION_SERVICE_STARTED, notification);
		}

		private void dismissServiceStartedNotification() {
		NotificationManager manager =
		(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		manager.cancel(NOTIFICATION_SERVICE_STARTED);
		}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		db.close();
	}
}
